﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ATEC.ATDataCoreNET;
using System.IO;
using SSDPNET;
using ATEC.GeometryNET;
using SSDPNET.DataCore;
using ATEC.ATDataCoreNET.ATObjects;
using DoModelExample;
using SSDPNET.Geom;
namespace DoDrawExample
{
    public class DrawingFile
    {

        /// <summary>
        /// 创建绘制文件  将种子文件复制到目标路径
        /// </summary>
        /// <param name="targetPath"></param>
        /// <returns></returns>
        public static bool CreateDrawingFile(string targetPath)
        {
            //获取出图种子文件 将其拷贝到出图目录下改名为出图文件名
            string strExePath = ConfigurationManager.GetVariable("_ROOTDIR", CfgVarLvl.User);
            string seedStr = strExePath + "ProjectExample\\Resource\\DrawingSeed.db";
            string fileName = Path.GetFileName(seedStr);
            FileInfo file = new FileInfo(seedStr);
            if (file.Exists)
            {
                file.CopyTo(targetPath, true);
            }
            else
            {
                string errorMessage = "未找到种子文件, 请将DrawingSeed.db放到相应目录下面。";
                string errorMessageTitle = "无种子文件";
                ATOutputFuncs.OutputMessageCenter(ATOutputFuncs.OutputMessagePriority.Error, errorMessage,
                      errorMessageTitle, ATOutputFuncs.OutputMessageAlert.Balloon);
                return false;
            }

            return true;
        }

        /// <summary>
        /// 打开工程
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="openMode"></param>
        /// <returns></returns>
        public static ATProject OpenATProject(string filePath, ATProjectOpenMode openMode)
        {
            string fileName = Path.GetFileName(filePath);
            ATProjectStatus fileStatus;
            ATDoc dbDoc = ATDoc.CreateFromFileName(out fileStatus, filePath, fileName, -100, ATDoc.FetchMode.Write, ATDoc.FetchOptions.Default);

            if (dbDoc.DocState == ATDoc.State.DoesNotExist)
            {
                string errorMessage = "创建ATDoc失败。";
                string errorMessageTitle = "创建ATDoc失败";
                ATOutputFuncs.OutputMessageCenter(ATOutputFuncs.OutputMessagePriority.Error, errorMessage,
                      errorMessageTitle, ATOutputFuncs.OutputMessageAlert.Balloon);
                return null;
            }

            ATProjectOwner dbFileOwner = ATProject.Create(dbDoc, openMode);
            ATProject dbFile = dbFileOwner.ATProject;
            StatusInt openStatus;
            ATProjectStatus status = dbFile.LoadATProject(out openStatus);
            if (ATProjectStatus.Success != status)
            {
                string errorMessage = "加载ATProject失败。";
                string errorMessageTitle = "加载ATProject失败";
                ATOutputFuncs.OutputMessageCenter(ATOutputFuncs.OutputMessagePriority.Error, errorMessage,
                      errorMessageTitle, ATOutputFuncs.OutputMessageAlert.Balloon);
                return null;
            }

            dbFile.FillDictionaryScene();
            return dbFile;
        }
        /// <summary>
        /// 场景参照
        /// </summary>
        /// <param name="destProject"></param>
        /// <param name="sourceScene"></param>
        /// <param name="origin"></param>
        /// <param name="scale"></param>
        /// <param name="rot"></param>
        /// <param name="useAnnotScale"></param>
        /// <returns></returns>
        public static StatusInt AttachDbScene(ATProject destProject, ATScene sourceScene , XPoint3d origin,
                double scale, XMatrix3d rot, bool useAnnotScale)
        {
            ATScene destScene = GetDefaultScene(destProject);
            string filePath = destProject.GetFileName();
            string sourcePath = sourceScene.GetATProject().GetFileName();

            ATDocMoniker atDoc = ATDocMoniker.CreatePortableMoniker(null,
                        sourcePath,                 //被参照的db文件路径
                       filePath,    //获取当前db文件路径
                           null, null, RelativePathPreference.CreateIfPossible);

            //创建ATAttachment  并设置相关信息
            ATAttachment attach = destScene.CreateATAttachment(atDoc, sourceScene.SceneName);

            if (attach == null)
            {
                return StatusInt.Error;
            }
            attach.ChangeOrientation(sourceScene.SceneName, RefAttachMethod.ATTACHMETHOD_CoincidentWorld, scale, true, true, true);
            attach.SetXRotMatrix(rot);
            attach.SetMasterOrigin(origin);
            attach.SetLocateLock(true);
            attach.SetSnapLock(true);
            attach.StoredScale = scale;
            attach.NestDepth = 99;
            attach.SetUseAnnotationScale(useAnnotScale);

            if (StatusInt.Success != attach.WriteToScene(false))
            {
                string errorMessage = "参照文件失败。";
                string errorMessageTitle = "参照文件失败";
                ATOutputFuncs.OutputMessageCenter(ATOutputFuncs.OutputMessagePriority.Error, errorMessage,
                      errorMessageTitle, ATOutputFuncs.OutputMessageAlert.Balloon);
                return StatusInt.Error;
            }
            SSDPNET.ATView.ViewUpdateSingle(2);
            return StatusInt.Success;

        }
        /// <summary>
        /// 获取默认场景
        /// </summary>
        /// <param name="dbFile"></param>
        /// <returns></returns>
        public static ATScene GetDefaultScene(ATProject dbFile)
        {
            SceneID sceneId = dbFile.DefaultSceneId;
            StatusInt status;
            ATScene dbScene = dbFile.LoadRootSceneById(out status, sceneId, true, true, true);

            string nm = dbScene.SceneName;
            string fNm = dbScene.GetATProject().GetFileName();
            bool bIs3D = dbScene.Is3d;

            return dbScene;
        }
        /// <summary>
        /// 添加图框
        /// </summary>
        /// <param name="ptOr"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public static bool AddFrame(XPoint3d ptOr, ATProject file)
        {
            string strExePath = ConfigurationManager.GetVariable("_ROOTDIR", CfgVarLvl.User);
            string frameDirPath = strExePath + "ProjectExample\\Resource\\DrawingFrame.db";
            string frameName = Path.GetFileName(frameDirPath);
            ATProject frameFile = OpenATProject(frameDirPath, ATProjectOpenMode.ReadOnly);
            if (frameFile == null)
                return false;
            ATScene frameScene = GetDefaultScene(frameFile);
            if (!frameScene.IsValid())
            {
                return false;
            }
            ATScene destScene = GetDefaultScene(file);
            if (!destScene.IsValid())
            {
                return false;
            }
            SceneInfo sceneInfo = destScene.GetSceneInfo();
            //比例
            sceneInfo.AnnotationScaleFactor = 100;
            if (ATScenesStatus.Success != destScene.SetSceneInfo(sceneInfo))
                return false;
            SSDPNET.ScaleSta.SceneRefPropagateAnnotationScale(destScene);

            StatusInt status = AttachDbScene(file,  frameScene, ptOr, 100, XMatrix3d.Identity, true);
         
            file.ProcessChanges(ATSaveReason.ApplicationInitiated);
            if (status != StatusInt.Success)
                return false;

            return true;
        }

        /// <summary>
        /// 创建场景
        /// </summary>
        /// <param name="sceneName"></param>
        /// <param name="dbFile"></param>
        /// <param name="annotationScaleFactor"></param>
        /// <param name="type"></param>
        /// <returns></returns>

        public static ATScene CreateScene(string sceneName, ATProject dbFile, double annotationScaleFactor,
      ATScenesType type)
        {
            ATScene defaultScene = GetDefaultScene(dbFile);
            ATScenesStatus scenelStatus;
            string path = dbFile.GetFileName();
            bool is3d = true;
            if (ATScenesType.Drawing == type || ATScenesType.Sheet == type)
                is3d = false;
            ATScene dbScene = dbFile.CreateNewScene(out scenelStatus, sceneName, type, is3d, defaultScene);
            if (ATScenesStatus.Success != scenelStatus || dbScene == null)
                return null;


            SceneInfo sceneInfo = dbScene.GetSceneInfo();
            //比例
            sceneInfo.Description = sceneName;
            sceneInfo.PropagateAnnotationScale = true;
            sceneInfo.AnnotationScaleFactor = annotationScaleFactor;
            if (ATScenesStatus.Success != dbScene.SetSceneInfo(sceneInfo))
                return null;

            dbScene.GetATProject().ProcessChanges(ATSaveReason.ApplicationInitiated);
            return dbScene;
        }


 
    }
}
